package com.chengh.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.chengh.common.to.es.SkuEsModel;
import com.chengh.gulimall.search.config.GulimallElasticSearchConfig;
import com.chengh.gulimall.search.constant.EsConstant;
import com.chengh.gulimall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {

        //将数据保存到ES中
        // 1.给es中建立索引,建立好映射关系(此步骤在Kibabn中已经建立好了)

        //2.给ES中保存这些数据
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {
            // 构造保存请求
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);//指定索引
            indexRequest.id(skuEsModel.getSkuId().toString());//指定id
            String s = JSON.toJSONString(skuEsModel);
            indexRequest.source(s, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);//BulkRequest bulkRequest, RequestOptions options
        boolean b = bulk.hasFailures();//是否有错误
        if (b) {
            List<String> collect = Arrays.stream(bulk.getItems()).map(item -> {
                return item.getId();
            }).collect(Collectors.toList());
            log.error("商品上架错误: {}",collect);
        }

        return b;
    }
}
